<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
        <!--仓库数据-->
        <pane size="16">
          <el-col>
            <div class="head-container">
              <el-input v-model="deptName" placeholder="请输入仓库名称" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" />
            </div>
            <div class="head-container">
              <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current @node-click="handleNodeClick" />
            </div>
          </el-col>
        </pane>
        <!--仓库数据-->
        <pane size="84">
          <el-col>
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
              <el-form-item label="仓库名称" prop="name">
                <el-input
                  v-model="queryParams.name"
                  placeholder="请输入仓库名称"
                  clearable
                  @keyup.enter.native="handleQuery"
                />
              </el-form-item>
              <el-form-item label=" 状态" prop="state">
                <el-select v-model="queryParams.state" placeholder="请选择 状态" clearable>
                  <el-option
                    v-for="dict in dict.type.state"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  type="primary"
                  plain
                  icon="el-icon-plus"
                  size="mini"
                  @click="handleAdd"
                  v-hasPermi="['system:stocks:add']"
                >新增</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="success"
                  plain
                  icon="el-icon-edit"
                  size="mini"
                  :disabled="single"
                  @click="handleUpdate"
                  v-hasPermi="['system:stocks:edit']"
                >修改</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="danger"
                  plain
                  icon="el-icon-delete"
                  size="mini"
                  :disabled="multiple"
                  @click="handleDelete"
                  v-hasPermi="['system:stocks:remove']"
                >删除</el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  type="warning"
                  plain
                  icon="el-icon-download"
                  size="mini"
                  @click="handleExport"
                  v-hasPermi="['system:stocks:export']"
                >导出</el-button>
              </el-col>
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>

            <el-table v-loading="loading" :data="stocksList" @selection-change="handleSelectionChange" border>
              <el-table-column type="selection" width="55" align="center" />
              <el-table-column label="id" align="center" prop="id" v-if="false" />
              <el-table-column label="仓库名称" align="center" prop="name" />
              <el-table-column label=" 仓库编码" align="center" prop="number" />
              <el-table-column label=" 位置" align="center" prop="position" />
              <el-table-column label=" 状态" align="center" prop="state">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.state" :value="scope.row.state"/>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleUpdate(scope.row)"
                    v-hasPermi="['system:stocks:edit']"
                  >修改</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                    v-hasPermi="['system:stocks:remove']"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <pagination
              v-show="total>0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
            />

            <!-- 添加或修改仓库管理对话框 -->
            <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
              <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="仓库名称" prop="name">
                  <el-input v-model="form.name" placeholder="请输入仓库名称" />
                </el-form-item>
                <el-form-item label=" 仓库编码" prop="number">
                  <el-input v-model="form.number" placeholder="请输入 仓库编码" />
                </el-form-item>
                <el-form-item label=" 位置" prop="position">
                  <el-input v-model="form.position" placeholder="请输入 位置" />
                </el-form-item>
                <el-form-item label=" 上级仓库" prop="position">
                  <el-select v-model="form.pid" placeholder="请选择上级仓库" clearable filterable @change="handleStockInfoChange">
                    <el-option
                      v-for="driver in this.stockInfoList"
                      :key="driver.id"
                      :label="driver.name"
                      :value="driver.id"
                    />
                  </el-select>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
              </div>
            </el-dialog>
          </el-col>
        </pane>
      </splitpanes>
    </el-row>
  </div>
</template>

<script>
import { listStocks, getStocks, delStocks, addStocks, updateStocks,getStocksInfoList,stockTreeSelect } from "@/api/system/stocks"
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"

export default {
  name: "Stocks",
  dicts: ['state'],
  components: { Treeselect, Splitpanes, Pane },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 仓库管理表格数据
      stocksList: [],
      stockInfoList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 部门树选项
      deptOptions: undefined,
      // 部门名称
      deptName: undefined,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        state: null,
        pid: undefined
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {}
    }
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getList()
    this.getDeptTree()
    this.handleStockInfo('')
  },
  methods: {
    /** 查询部门下拉树结构 */
    getDeptTree() {
      stockTreeSelect().then(response => {
        this.deptOptions = response.data
        this.enabledDeptOptions = this.filterDisabledDept(JSON.parse(JSON.stringify(response.data)))
      })
    },
    // 过滤禁用的部门
    filterDisabledDept(deptList) {
      return deptList.filter(dept => {
        if (dept.disabled) {
          return false
        }
        if (dept.children && dept.children.length) {
          dept.children = this.filterDisabledDept(dept.children)
        }
        return true
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.pid = data.id
      this.handleQuery()
    },
    handleStockInfo(param){
      this.getStockInfoList(param);
    },

    handleStockInfoChange(id){
        if (id) {
          // 根据选中的货物ID查找对应的货物信息
          const selectedGoods = this.stockInfoList.find(goods => goods.id === id);
          if (selectedGoods) {
            // 设置货物规格（禁用状态）
            this.form.pid = selectedGoods.id || '';
            this.form.pidPath = selectedGoods.pidPath || '';
          }
        } else {
          // 清空选择时，重置相关字段
          this.form.pid = '';
          this.form.pidPath =  '';
        }

    },

    /** 获取司机列表 */
    getStockInfoList(param) {
      // 这里需要替换为实际的API调用
      getStocksInfoList(param).then(response => {
        this.stockInfoList = response.rows
      })
    },

    /** 查询仓库管理列表 */
    getList() {
      this.loading = true
      listStocks(this.queryParams).then(response => {
        this.stocksList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        tenantId: null,
        createTime: null,
        updateTime: null,
        createUserId: null,
        createOrgId: null,
        createUserName: null,
        updateUserId: null,
        updateUserName: null,
        isDelete: null,
        orgId: null,
        sqare01: null,
        sqare02: null,
        sqare03: null,
        sqare04: null,
        sqare05: null,
        sqare06: null,
        name: null,
        number: null,
        shortNumber: null,
        pid: null,
        pidPath: null,
        type: null,
        address: null,
        position: null,
        controlQty: null,
        contactId: null,
        state: null,
        createOrgName: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.queryParams.pid = undefined
      this.$refs.tree.setCurrentKey(null)
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.handleStockInfo('')
      this.open = true
      this.title = "添加仓库管理"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.handleStockInfo('')
      const id = row.id || this.ids
      getStocks(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改仓库管理"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateStocks(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addStocks(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除仓库管理编号为"' + ids + '"的数据项？').then(function() {
        return delStocks(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/stocks/export', {
        ...this.queryParams
      }, `stocks_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
